class GameView {
    constructor() {
        this.initializeElements();
        this.bindEventHandlers();
        this.createPositionDialog();
    }

    initializeElements() {
        this.elements = {
            loading: document.getElementById('loading'),
            attributeDialog: document.getElementById('attribute-dialog'),
            playerLife: document.getElementById('player-life'),
            robotLife: document.getElementById('robot-life'),
            battleLog: document.getElementById('battle-log'),
            phaseButton: document.getElementById('phase-button'),
            surrender: document.getElementById('surrender'),
            playerHand: document.getElementById('player-hand'),
            playerMonsterZone: document.getElementById('player-monster-zone'),
            playerMagicZone: document.getElementById('player-magic-zone'),
            robotHand: document.getElementById('robot-hand'),
            robotMonsterZone: document.getElementById('robot-monster-zone'),
            robotMagicZone: document.getElementById('robot-magic-zone'),
            playerDeck: document.getElementById('player-deck'),
            robotDeck: document.getElementById('robot-deck'),
            playerGraveyard: document.getElementById('player-graveyard'),
            robotGraveyard: document.getElementById('robot-graveyard'),
            positionDialog: null
        };
    }

    bindEventHandlers() {
        this.onAttributeSelect = null;
        this.onPhaseEnd = null;
        this.onSurrender = null;
        this.onCardSelect = null;
        this.onMonsterSelect = null;
        this.onMagicSelect = null;
        this.onDirectAttack = null;

        // 修改按钮事件绑定
        this.elements.phaseButton.onclick = () => {
            if (this.onPhaseEnd) {
                this.onPhaseEnd();
            }
        };

        this.elements.surrender.onclick = () => {
            if (this.onSurrender) {
                this.onSurrender();
            }
        };
    }

    // UI更新方法
    showLoading() {
        this.elements.loading.style.display = 'flex';
    }

    hideLoading() {
        this.elements.loading.style.display = 'none';
    }

    showAttributeSelection() {
        this.elements.attributeDialog.style.display = 'block';
        const buttons = this.elements.attributeDialog.querySelectorAll('button');
        buttons.forEach(button => {
            button.onclick = (e) => {
                e.preventDefault();
                if (this.onAttributeSelect) {
                    this.onAttributeSelect(button.dataset.attribute);
                }
            };
        });
    }

    hideAttributeSelection() {
        this.elements.attributeDialog.style.display = 'none';
    }

    updateLifePoints(player, points) {
        const element = player === 'player' ? this.elements.playerLife : this.elements.robotLife;
        element.textContent = points;
    }

    updateCardZones(gameState) {
        // 使用 DocumentFragment 减少DOM操作
        const updateZone = (elementId, cards, hidden = false) => {
            const zone = document.getElementById(elementId);
            const fragment = document.createDocumentFragment();
            
            // 如果是机器人的手牌区域，只显示卡牌数量
            if (elementId === 'robot-hand') {
                const cardCount = cards.length;
                zone.innerHTML = cardCount > 0 ? `手牌数量：${cardCount}` : '';
                return;
            }

            cards.forEach(card => {
                const cardElement = this.createCardElement(card, hidden);
                this.bindCardEvents(cardElement, card, elementId);
                fragment.appendChild(cardElement);
            });

            zone.innerHTML = '';
            zone.appendChild(fragment);
        };

        // 批量更新所有区域
        requestAnimationFrame(() => {
            const zones = [
                { id: 'player-hand', cards: gameState.playerHand },
                { id: 'player-monster-zone', cards: gameState.playerMonsterZone },
                { id: 'player-magic-zone', cards: gameState.playerMagicZone },
                { id: 'robot-hand', cards: gameState.robotHand },
                { id: 'robot-monster-zone', cards: gameState.robotMonsterZone },
                { id: 'robot-magic-zone', cards: gameState.robotMagicZone }
            ];

            zones.forEach(({ id, cards, hidden }) => {
                updateZone(id, cards, hidden);
            });

            // 更新计数器
            this.updateZoneCount('player-deck', gameState.playerDeckCount);
            this.updateZoneCount('robot-deck', gameState.robotDeckCount);
            this.updateZoneCount('player-graveyard', gameState.playerGraveyardCount);
            this.updateZoneCount('robot-graveyard', gameState.robotGraveyardCount);
        });
    }

    updateZoneCount(elementId, count) {
        const element = document.getElementById(elementId);
        if (element) {
            element.textContent = `${element.textContent.split('(')[0]}(${count})`;
        }
    }

    showMessage(message, type = 'info') {
        requestAnimationFrame(() => {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${type}`;
            messageDiv.textContent = message;
            document.body.appendChild(messageDiv);

            // 使用 requestAnimationFrame 处理动画
            requestAnimationFrame(() => {
                messageDiv.style.opacity = '1';
                setTimeout(() => {
                    messageDiv.style.opacity = '0';
                    setTimeout(() => messageDiv.remove(), 300);
                }, 2000);
            });
        });
    }

    clearSelection() {
        document.querySelectorAll('.card.selected').forEach(card => {
            card.classList.remove('selected');
        });
    }

    markCardAsAttackable(cardElement) {
        cardElement.classList.add('attackable');
    }

    unmarkAllCards() {
        document.querySelectorAll('.card.attackable').forEach(card => {
            card.classList.remove('attackable');
        });
    }

    createCardElement(card, hidden = false) {
        const cardDiv = document.createElement('div');
        cardDiv.className = `card ${card.type}`;
        cardDiv.setAttribute('data-card-id', card.id);
        cardDiv.setAttribute('data-position', card.position || 'attack');

        const attributeColors = {
            '金': 'var(--gold-color)',
            '木': 'var(--wood-color)',
            '水': 'var(--water-color)',
            '火': 'var(--fire-color)',
            '土': 'var(--earth-color)'
        };
        
        cardDiv.style.borderColor = attributeColors[card.attribute];

        if (!hidden) {
            cardDiv.innerHTML = `
                <div class="card-name">${card.name}</div>
                ${card.type === 'monster' ? `
                    <div class="card-stats">
                        <div>攻击力: ${card.stats.attack}</div>
                        <div>防御力: ${card.stats.defense}</div>
                        <div>生命值: ${card.stats.health}</div>
                    </div>
                ` : `
                    <div class="card-effect">
                        ${this.getEffectDescription(card.effect)}
                    </div>
                `}
                <div class="card-info">
                    <div>${card.description}</div>
                    <div>属性: ${card.attribute}</div>
                    ${card.type === 'monster' ? `
                        <div>状态: ${card.position === 'defense' ? '防御' : '攻击'}</div>
                    ` : ''}
                </div>
            `;
        } else {
            cardDiv.innerHTML = '<div class="card-back">卡牌背面</div>';
        }

        return cardDiv;
    }

    getEffectDescription(effect) {
        const effectTypes = {
            'attack': '攻击力',
            'defense': '防御力',
            'health': '生命值'
        };
        return `增加${effectTypes[effect.type]} +${effect.value}`;
    }

    logMessage(message) {
        const div = document.createElement('div');
        div.textContent = message;
        this.elements.battleLog.appendChild(div);
        this.elements.battleLog.scrollTop = this.elements.battleLog.scrollHeight;
    }

    showGameResult(winner) {
        const resultDiv = document.createElement('div');
        resultDiv.className = 'game-result';
        resultDiv.textContent = `${winner}获得胜利！`;
        document.body.appendChild(resultDiv);
        return resultDiv;
    }

    // 修改控制按钮状态方法
    enableControls(state) {
        const { phaseButton, surrender } = this.elements;
        
        switch (state) {
            case 'placing':
                phaseButton.disabled = false;
                phaseButton.textContent = '结束放置阶段';
                break;
            case 'battle':
                phaseButton.disabled = false;
                phaseButton.textContent = '结束战斗阶段';
                break;
            default:
                phaseButton.disabled = true;
                phaseButton.textContent = '结束当前阶段';
        }
        
        surrender.disabled = false;
    }

    bindCardEvents(cardElement, card, zoneId) {
        if (zoneId.startsWith('player-')) {
            switch (zoneId) {
                case 'player-hand':
                    cardElement.onclick = async () => {
                        if (this.onCardSelect) {
                            if (card.type === 'monster') {
                                const position = await this.showPositionDialog();
                                if (position) {  // 如果没有取消
                                    this.onCardSelect(card, position);
                                }
                            } else {
                                this.onCardSelect(card);
                            }
                        }
                    };
                    break;

                case 'player-monster-zone':
                    cardElement.onclick = () => {
                        if (this.onMonsterSelect) {
                            this.selectCard(cardElement);
                            this.onMonsterSelect(card);
                        }
                    };
                    break;

                case 'player-magic-zone':
                    cardElement.onclick = () => {
                        if (this.onMagicSelect) {
                            this.selectCard(cardElement);
                            this.onMagicSelect(card);
                        }
                    };
                    break;
            }
        }

        // 为对手的怪兽区域添加事件（用于选择攻击目标）
        if (zoneId === 'robot-monster-zone') {
            cardElement.onclick = () => {
                if (this.onMonsterSelect) {
                    this.onMonsterSelect(card);
                }
            };
        }
    }

    selectCard(cardElement) {
        this.clearSelection();
        cardElement.classList.add('selected');
    }

    enableBattleTargets(canDirectAttack = false) {
        // 启用对手怪兽区域的点击
        const robotMonsters = this.elements.robotMonsterZone.children;
        Array.from(robotMonsters).forEach(monster => {
            this.markCardAsAttackable(monster);
        });

        // 如果可以直接攻击，添加直接攻击按钮
        if (canDirectAttack) {
            const attackButton = document.createElement('button');
            attackButton.className = 'direct-attack-btn';
            attackButton.textContent = '直接攻击玩家';
            attackButton.onclick = () => {
                if (this.onDirectAttack) {
                    this.onDirectAttack();
                }
            };
            this.elements.robotMonsterZone.appendChild(attackButton);
        }
    }

    disableBattleTargets() {
        this.unmarkAllCards();
        const attackButton = document.querySelector('.direct-attack-btn');
        if (attackButton) {
            attackButton.remove();
        }
    }

    // 添加创建对话框的方法
    createPositionDialog() {
        const dialog = document.createElement('div');
        dialog.className = 'position-dialog';
        dialog.innerHTML = `
            <h3>请选择怪兽表示形式</h3>
            <div class="buttons">
                <button class="attack">攻击表示</button>
                <button class="defense">守备表示</button>
                <button class="cancel">取消</button>
            </div>
        `;
        document.body.appendChild(dialog);
        this.elements.positionDialog = dialog;
    }

    // 修改卡牌选择处理方法
    async showPositionDialog() {
        return new Promise((resolve) => {
            const dialog = this.elements.positionDialog;
            const buttons = dialog.querySelectorAll('button');
            
            const handleClick = (position) => {
                dialog.style.display = 'none';
                buttons.forEach(btn => btn.onclick = null);
                resolve(position);
            };

            buttons[0].onclick = () => handleClick('attack');
            buttons[1].onclick = () => handleClick('defense');
            buttons[2].onclick = () => handleClick(null);

            dialog.style.display = 'block';
        });
    }
}

export { GameView };
